package com.lqian.demo01.wait_notify;

import com.lqian.utils.SleepHelper;

import java.util.Queue;

public class Consumer implements Runnable{
    private Queue<String> bags;
    private int size;

    public Consumer(Queue<String> bags, int size) {
        this.bags = bags;
        this.size = size;
    }

    @Override
    public void run() {
        while(true){
            synchronized (bags){
                //这里使用 while 而非 if 是为了防止虚假唤醒
                while(bags.isEmpty()){
                    System.out.println("bags is empty..");
                    try {
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                SleepHelper.sleepSeconds(1); //每一秒钟消费一个
                String bag = bags.remove();
                System.out.println("消费者：消费-"+bag);
                bags.notifyAll();
            }
        }
    }
}
